package com.example.pceb.controller;
import cn.hutool.db.PageResult;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.pceb.VO.ResumeSendVO;
import com.example.pceb.entity.*;
import com.example.pceb.response.PageResponse;
import com.example.pceb.result.Result;
import com.example.pceb.service.Impl.ResumeSendService;
import com.example.pceb.service.RecruitService;
import com.example.pceb.service.ResumeService;
import com.example.pceb.utils.PathUtils;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

@RestController
@RequestMapping("/resume")
//@CrossOrigin(origins = "*")
public class ResumeSendController {
    private static final Logger logger = LoggerFactory.getLogger(ResumeSendController.class);

    @Autowired
    private ResumeSendService resumeSendService;

    @Autowired
    private RecruitService recruitService;

    @Autowired
    private ResumeService resumeService;

    @Autowired
    private FileStorageProperties fileStorageProperties;

    private String saveDir;

    @Autowired
    private PathUtils pathUtils;


    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Value("${aliyun.oss.urlPrefix}")
    private String urlPrefix; // 形如 https://your-bucket.oss-cn-xxx.aliyuncs.com

    // 1. 上传PDF到OSS并投递简历
    @PostMapping("/sendPdf")
    public Result sendPdfResume(
            @RequestParam("file") MultipartFile file,
            @RequestParam("recruitId") Integer recruitId,
            @RequestParam("username") String username,
            @RequestParam("resumeJson") String resumeJson) {
        try {
            if (file.isEmpty()) return Result.error("请选择简历文件");
            String originalFileName = file.getOriginalFilename();
            if (originalFileName == null || !originalFileName.toLowerCase().endsWith(".pdf")) {
                return Result.error("仅支持PDF格式简历");
            }
            // 上传到OSS
            String objectName = "resume/" + UUID.randomUUID() + "_" + originalFileName;
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, objectName, file.getInputStream());
            ossClient.shutdown();
            String ossUrl = urlPrefix + objectName;

            // 保存投递记录
            ResumeSend send = new ResumeSend();
            send.setUsername(username);
            send.setRecruitId(recruitId);
            send.setResumePath(ossUrl); // 云端URL
            send.setOriginalFileName(originalFileName);
            send.setResumeDetail(resumeJson);
            send.setSendTime(new Date());
            resumeSendService.save(send);

            return Result.success("简历投递成功");
        } catch (Exception e) {
            return Result.error("简历上传失败: " + e.getMessage());
        }
    }

    // 2. 企业端分页获取收到的简历
    @GetMapping("/received")
    public PageResponse<ResumeSendVO> getReceivedResumes(
            @RequestParam String enterprise,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String studentName,
            @RequestParam(required = false) String recruitName) {

        // 获取企业所有职位ID
        QueryWrapper<Recruit> recruitQueryWrapper = new QueryWrapper<>();
        recruitQueryWrapper.eq("enterprise", enterprise);
        if (recruitName != null && !recruitName.isEmpty()) {
            recruitQueryWrapper.like("identity", recruitName);
        }
        List<Integer> recruitIds = recruitService.list(recruitQueryWrapper)
                .stream().map(Recruit::getId).collect(Collectors.toList());
        if (recruitIds.isEmpty()) return PageResponse.empty();

        Page<ResumeSend> sendPage = new Page<>(page, size);
        QueryWrapper<ResumeSend> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("recruit_id", recruitIds).orderByDesc("send_time");
        if (studentName != null && !studentName.isEmpty()) {
            queryWrapper.like("username", studentName);
        }
        IPage<ResumeSend> pageResult = resumeSendService.page(sendPage, queryWrapper);

        List<ResumeSendVO> vos = pageResult.getRecords().stream().map(send -> {
            ResumeSendVO vo = new ResumeSendVO();
            BeanUtils.copyProperties(send, vo);
            Resume resume = resumeService.getOne(
                    new QueryWrapper<Resume>().eq("username", send.getUsername()));
            if (resume != null) {
                vo.setStudentName(resume.getName());
                vo.setStudentPhone(resume.getPhone());
                vo.setStudentEmail(resume.getEmail());
                vo.setAvatarUrl(resume.getAvatarUrl());
            }
            Recruit recruit = recruitService.getById(send.getRecruitId());
            if (recruit != null) {
                vo.setRecruitName(recruit.getIdentity());
                vo.setEnterprise(recruit.getEnterprise());
            }
            return vo;
        }).collect(Collectors.toList());

        return new PageResponse<>(pageResult, vos);
    }

    // 3. 企业端获取简历详情
    @GetMapping("/detail")
    public Map<String, Object> getResumeDetail(@RequestParam Integer id) {
        ResumeSend send = resumeSendService.getById(id);
        Map<String, Object> result = new HashMap<>();
        if (send != null && send.getResumeDetail() != null) {
            result.put("resumeDetail", send.getResumeDetail());
        }
        return result;
    }

    // 4. 企业端下载简历（直接返回云端URL即可，前端直接跳转resumePath）
    @GetMapping("/download/{id}")
    public Map<String, Object> downloadResume(@PathVariable Integer id) {
        ResumeSend send = resumeSendService.getById(id);
        Map<String, Object> result = new HashMap<>();
        if (send != null && send.getResumePath() != null) {
            result.put("url", send.getResumePath());
        }
        return result;
    }
    //学生查询发送简历的状态
    @GetMapping("/sendRecords")
    public Result<List<ResumeSendVO>> getSendRecords(@RequestParam String username) {
        // 查询该学生所有投递记录
        List<ResumeSend> sendList = resumeSendService.list(
                new QueryWrapper<ResumeSend>().eq("username", username).orderByDesc("send_time")
        );

        // 转换为VO，补充职位和企业信息
        List<ResumeSendVO> voList = sendList.stream().map(send -> {
            ResumeSendVO vo = new ResumeSendVO();
            BeanUtils.copyProperties(send, vo);
            vo.setStatus(send.getStatus());
            vo.setInterviewContent(send.getInterviewContent());

            // 查询职位信息
            Recruit recruit = recruitService.getById(send.getRecruitId());
            if (recruit != null) {
                vo.setRecruitName(recruit.getIdentity());
                vo.setEnterprise(recruit.getEnterprise());
            }
            // 这里假设status字段已在ResumeSend中，1=面试通知，2=拒绝，0=待处理
            return vo;
        }).collect(Collectors.toList());

        return Result.success(voList);
    }

    //企业修改简历投递状态
    @PostMapping("/updateStatus")
    public Result updateStatus(@RequestBody Map<String, Object> params) {
        Integer id = Integer.valueOf(params.get("id").toString());
        Integer status = Integer.valueOf(params.get("status").toString());
        String interviewContent = params.get("interviewContent") != null ? params.get("interviewContent").toString() : null;
        ResumeSend send = resumeSendService.getById(id);
        if (send == null) return Result.error("记录不存在");
        send.setStatus(status);
        if (interviewContent != null) {
            send.setInterviewContent(interviewContent);
        }
        resumeSendService.updateById(send);
        return Result.success();
    }
}